/** *******************************************************************
 * FlexDatabaseManager
 * Copyright (c) 2008 Jonnie Spratley. All Rights Reserved.
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.query
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.commands.SequenceCommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.query.ExecuteQueryEvent;
	import com.jonniespratley.flexdatabasemanager.events.query.ExplainQueryEvent;
	import com.jonniespratley.flexdatabasemanager.factories.FlexDatabaseManagerFactory;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class ExecuteQueryCommand extends SequenceCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		override public function execute( event:CairngormEvent ) : void
		{
			model.interactingWithServer = true;
			
			var evt:ExecuteQueryEvent = event as ExecuteQueryEvent;
			var delegate:FlexDatabaseManagerDelegate = new FlexDatabaseManagerDelegate( this );
			
			this.nextEvent = evt.nextEventSequence;
			
			if ( evt.aQuery == null )
			{
				Alert.show( 'You must write a query to execute it!', 'Alert' );
			} else {
				delegate.executeQuery( model.currentUser, evt.aQuery );				
			}
		}
		
		public function result( data:Object ) : void
		{
			model.interactingWithServer = false;
			
			var result:ResultEvent = data as ResultEvent;
			model.queryJSONCollection = result.result as String;
			model.queryCollection = FlexDatabaseManagerFactory.parseJSONResult( data.result );
			
			ExplainQueryEvent( nextEvent );
			executeNextCommand();
			
			trace( 'Sequence Event: Calling on ExplainQueryEvent' );
		}

		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			var faultEvt:FaultEvent = fault as FaultEvent;
			Alert.show(faultEvt.fault.toString(), "Error");
			trace(faultEvt.fault.faultString);
		}

	}
}
